import { getStatus } from "../../api/guide"
import { getVideoList } from "../../api/video"
import { VideoItem } from '../../api/video'
import { isLogin, login } from '../../utils/login'
import { getTrainTaskData, getTrainProjectList } from '../../api/train'

Page({
  /**
   * 页面的初始数据
   */
  data: <{
    isShow: boolean,
    content: string,
    active: number | string,
    doctorList: {
      id: string;
      name: string;
      hospital: string;
      avatar: string;
      guideList: VideoItem[];
    }[],
    videoList: Array<VideoItem>
    projectList: Array<any>,
    score: {
      totalNum: number,
      incompleteNum: number,
      diffRate: string
    },
    project: {
      pageNum: number,
      pageSize: number,
      name: string
    }
  }>{
    isShow: false,
    content: '',
    active: 2,
    currentDoctorGuide: [],
    doctorList: [],
    videoList: [],
    projectList: [],
    score: {
      totalNum: 0,
      incompleteNum: 0,
      diffRate: '0'
    },
    project: {
      pageNum:1,
      pageSize: 200,
      name: ''
    }
  },

  async onLoad(){
    this.getList()
  },

  onShow(){
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
    this.setData({
      currentDoctorGuide: []
    })

    if(isLogin()){
      const userInfo = login()
      if(userInfo){
        this.handleLoginAction(userInfo);
      }
      getStatus().then(res => {
        if(res.data){
          this.setData({
            isShow: res.data.status === '0'
          })
        }
      })

      this.getList()
      this.getProjectList()
      this.getTrainData()
    }
  },

  handleLoginAction(userInfo: any){
    this.setData({
      userInfo: userInfo,
      logined: true,
    })
  },


  getTrainData(){
    getTrainTaskData().then((res: any) => {
      if(res && res.data){
        const {totalNum, incompleteNum, diffRate} = res.data
        this.setData({
          score: {
            totalNum, incompleteNum, diffRate: Number(diffRate).toFixed(1)
          }
        })
      }
    })
  },

  getProjectList(){
    getTrainProjectList({
      pageNum: this.data.project.pageNum,
      pageSize: this.data.project.pageSize,
      taskName: this.data.project.name
    }).then((res: any) => {
      if(res && res.rows.length > 0){
        this.setData({
          projectList: res.rows
        })
      }
    })
  },

  inputHandle(e: any){
    const value = e.detail.value;
    this.setData({
      content: value
    })
    if(value === ''){
      setTimeout(() => {
        this.getList()
      }, 0)
    }
  },

  async getList(){
    const res = await getVideoList({
      pageSize: 999,
      pageNum: 1,
      title: this.data.content
    })

    if(res && res.rows){
      const {videoList, doctorList} = this.setOriginData(res.rows as VideoItem[])
      this.setData({
        videoList,
        doctorList
      })
    }
  },

  createHandle(){
    wx.navigateTo({
      url: '/pages/createVideo/createVideo',
      events: {
        acceptDataFromOpenerPage: function (data: any) {
          console.log(data)
        }
      },
      success: (res) => {
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          data: {
            id: 1
          }
        })
      }
    });
  },

  setOriginData(info: Array<VideoItem>){
    const priorityNames = ['樊代明', '大肠癌专业委员会', '肺癌专业委员会', '乳腺癌专业委员会', '胃癌专业委员会', '肝癌专业委员会'];

    const mappedData = Array.from(new Set(info.map(item => item.name))).map(name => {
      const group = info.filter(item => item.name === name);
      return {
        id: group[0].id,
        name: name.replace('中国抗癌协会', ''),
        hospital: group[0].hospital,
        avatar: '',
        guideList: group
      };
    });

    const sortedData = mappedData.sort((a, b) => {
      const indexA = priorityNames.indexOf(a.name);
      const indexB = priorityNames.indexOf(b.name);

      if (indexA !== -1 && indexB !== -1) {
        return indexA - indexB;
      }
      if (indexA !== -1) {
        return -1;
      }
      if (indexB !== -1) {
        return 1;
      }
      return 0;
    });
    return {
      videoList: info, 
      doctorList: sortedData
    }
  },

  searchHandle(e: any){
    const value = e.detail.value.trim();
    this.setData({
      content: value
    })

    setTimeout(async () => {
      await this.getList()
      const newInfo = this.data.videoList.filter(item => {
        return item.name && item.hospital && (item.name.indexOf(value) > -1 || item.hospital.indexOf(value) > -1)
      })
      this.setData({
        videoList: newInfo
      })
  
      const newDoctor = this.data.doctorList.filter(item => {
        return item.name && item.hospital && (item.name.indexOf(value) > -1 || item.hospital.indexOf(value) > -1)
      })
      this.setData({
        doctorList: newDoctor
      })
    }, 0)
  },

  searchClick(){
    setTimeout(() => {
      this.searchHandle({
        detail: {
          value: this.data.content
        }
      })
    }, 100)
  },

  changeTabHandle(e: any){
    const index = e.currentTarget.dataset.index as string

    this.setData({
      active: index
    })

    setTimeout(() => {
      if(index === '3'){
        this.getTrainData()
        this.getProjectList()
      }
    }, 0)
  },

  openTrainProjectDetail(e: any){
    const data = e.currentTarget.dataset.item;
    const currDate = new Date().toISOString().slice(0, 10)
    const start = new Date(data.beginDate);
    const end = new Date(data.endDate);
    const now = new Date(currDate);

    // if(now < start){
    //   wx.showToast({
    //     title: '项目还未开始',
    //     icon: 'none'
    //   });
    //   return;
    // }

    // if(now > end){
    //   wx.showToast({
    //     title: '项目已经结束',
    //     icon: 'none'
    //   });
    //   return;
    // }

    wx.navigateTo({
      url: '/pages/project/project?title=' + data.name,
      success: (res) => {
        res.eventChannel.emit('acceptDataFromOpenerPage', e.currentTarget.dataset.item)
      }
    });
  },


  showGuide(e: any){
    const { index } = e.currentTarget.dataset
    this.setData({
      currentDoctorGuide: this.data.doctorList[index].guideList
    })
  },

  openDetail(e: any){
    wx.navigateTo({
      url: '/pages/guideDetail/guideDetail',
      success: (res) => {
        res.eventChannel.emit('acceptDataFromOpenerPage', e.currentTarget.dataset.item)
      }
    });
  },

  joinHandle(data: any){
    const conference = data.currentTarget.dataset.conference

    this.setData({
      currentWebinar: conference,
      showJoinWebinarDialog: true
    })
  },

  closeJoinWebinarDialog(){
    this.setData({
      showJoinWebinarDialog: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    try {
      this.data.requestTask.abort()
    } catch (error) {
      console.log('还没发请求就退出了，正常不会有影响')
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      "title": "",
      "path": `pages/home/home?active=1`,
      "imageUrl": "/static/img/home.jpg"
    }
  }
})